package com.thermoberg.zhousi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.stereotype.Component;

/**
 * Created by zhaoyou on 11/13/14.
 */

@Component
public class CrytoDemo {



    @Autowired
    private Environment env;

    public String textToEncrypt(String text) {
        final String password = env.getProperty("cryto.password");//"I AM SHERLOCKED";
        final String salt = env.getProperty("cryto.salt");//"bf178bd229544206";// KeyGenerators.string().generateKey();

        TextEncryptor encryptor = Encryptors.text(password, salt);


        String encryptedText = encryptor.encrypt(text);


        return encryptedText;
    }

    public String decrypt(String encryptedText) {
        final String password = env.getProperty("cryto.password");//"I AM SHERLOCKED";
        final String salt = env.getProperty("cryto.salt");//"bf178bd229544206";// KeyGenerators.string().generateKey();
        // Could reuse encryptor but wanted to show reconstructing TextEncryptor
        TextEncryptor decryptor = Encryptors.text(password, salt);
        String decryptedText = decryptor.decrypt(encryptedText);


        return decryptedText;

    }


    public static void main(String[] args) {
//        final String password = "I AM SHERLOCKED";
//        final String salt = KeyGenerators.string().generateKey();
//
//        TextEncryptor encryptor = Encryptors.text(password, salt);
//        System.out.println("Salt: \"" + salt + "\"");
//
//        String textToEncrypt = "*royal secrets*";
//        System.out.println("Original text: \"" + textToEncrypt + "\"");
//
//        String encryptedText = encryptor.encrypt(textToEncrypt);
//        System.out.println("Encrypted text: \"" + encryptedText + "\"");
//
//        // Could reuse encryptor but wanted to show reconstructing TextEncryptor
//        TextEncryptor decryptor = Encryptors.text(password, salt);
//        String decryptedText = decryptor.decrypt(encryptedText);
//        System.out.println("Decrypted text: \"" + decryptedText + "\"");

//        if(textToEncrypt.equals(decryptedText)) {
//            System.out.println("Success: decrypted text matches");
//        } else {
//            System.out.println("Failed: decrypted text does not match");
//        }
        CrytoDemo demo =  new CrytoDemo();
        //demo.decrypt(demo.textToEncrypt("zhaoyou:xxxx:123456789"));
        demo.decrypt("2f0f4311766abca8664cc9e6162c183589c36d29973527667282062e2fabeab4f988533583f9c806609761c1891d54a2");
    }
}